<template>
  <div>
    在线用户<br>
    <ul>
        <li v-for="(i,x) in userlist" :key="x"><el-button @click="fs(i.id)">{{ i.name }}</el-button></li>
    </ul>
    <el-input placeholder="请输入内容" v-model="yh"></el-input>
    <el-button @click="fa">发送</el-button>
    <div>
      聊天内容：
      <ul>
        <li v-for="(i,x) in meslst" :key="x">{{ i }}</li>
      </ul>
    </div>
  </div>
</template>

<script>
export default {
  data(){
    return{
      lst:"",
      ws:"",
      userid : 'kefu',
      username:'客服' + localStorage.getItem("name"),
      yh:"",
      meslst:[],
      userlist:[],
      cid:""

    }
  },
  mounted(){
    this.initweb()
  },
  methods:{
    initweb(){
      this.ws= new WebSocket("ws://localhost:8000/webs?id="+this.userid+"&username="+this.username)
      this.ws.onopen = function(){
        alert("success")
      }
      this.ws.onmessage = (data)=>{
        // 接收客服发的消息
        var mes = JSON.parse(data.data)
        this.meslst.push(mes["mm"])
        this.userlist = mes["userlist"]
      }
      this.ws.onclone = function(){
        alert("close")
      }
    },
    fs(id){
      this.cid = id
    },
    fa(){
      if(this.cid){
      var mm = this.username +"说"+this.yh
      this.meslst.push(mm)
      var sendmes = JSON.stringify({"id":this.cid,"mm":mm})
      this.ws.send(sendmes)
      }else{
        alert("必须选择要聊天的用户")
      }
      
    }

  }

}
</script>

<style>

</style>